<template>
  <el-container>
    <el-breadcrumb separator>
      <!--注册根机构-->
      <div class="mr-btn" style="position:absolute;top:30px;left:20px">
        <el-button class="golable-sty-btn" @click="openDialogVisible('create')" type="primary">注册</el-button>
      </div>
      <!-- <el-breadcrumb-item>机构管理</el-breadcrumb-item> -->
      <el-form label-width="120px" class="form-fliter" @submit.native.prevent>
      </el-form>
    </el-breadcrumb>
    <!-- main -->
    <el-main v-loading="isLoading ">
      <!-- table  -->
      <el-table
        class="orgTable mt-20"
        style="width: 100%;overflow-y:auto;"
        ref="table"
        row-key="orgId"
        stripe
        lazy
        height="calc(100vh - 200px)"
        :load="load"
        :data="tableData"
        :tree-props="{children: 'childs', hasChildren: 'hasChildren'}"
      >
        <el-table-column label="名称" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div style="width:50%;text-align:left;display:inline-block">
              <i class="ml5 mr5" :class="findOrgIcon(scope.row.orgType)"></i>
              <span style="vertical-align:middle">{{scope.row.orgName}}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="orgTypeStr" label="类别" width="180" :show-overflow-tooltip="true" />
        <el-table-column prop="orgCode" label="组织代码" :show-overflow-tooltip="true" />
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-container style="width:50%;margin:0 auto;">
              <div class="flex-1" v-if="scope.row.orgType==0">
                <el-tooltip class="item" effect="light" content="新增" placement="top">
                  <i style="color:#0090ff" class="iconfont icon-tianjia" @click="openDialogVisible('add',scope.row)"></i>
                </el-tooltip>
                &nbsp;&nbsp;  
              </div>
              <div class="flex-1">
                <el-tooltip class="item" effect="light" content="编辑" placement="top">
                  <i style="color:#0090ff" class="iconfont icon-xiugaibianji" @click="openDialogVisible('edit',scope.row)"></i>
                </el-tooltip>
                &nbsp;&nbsp;  
              </div>
              <div class="flex-1">
                <el-tooltip class="item" effect="light" content="删除" placement="top">
                  <i style="color:#0090ff" class="iconfont icon-shanchu" @click="deleteItem(scope.row,$event)"></i>
                </el-tooltip>
              </div>
            </el-container>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-footer>
       <div class="clearfix enc-pagination" style="padding:10px">
        <el-pagination
          class="mr-btn"
          background
          @current-change="pageChange"
           @size-change="handleSizeChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="prev, pager, next, jumper,sizes,total"
          :total="total">
        </el-pagination>
      </div>
    </el-footer>
    <AddOrUpdateOrgan ref="dialog" @callBack="dialogCallBack" />
  </el-container>
</template>

<script>
import { findSysOrgPage, getOrgTree, deleteSysOrg } from "../../api/organApi";
import AddOrUpdateOrgan from "./addOrUpdateOrgan";
import { throws } from "assert";

class TreeNode {
  constructor(opts) {
    this.comment = opts.comment;
    this.createTime = opts.createTime;
    this.orgCode = opts.orgCode;
    this.orgId = opts.orgId;
    this.orgLevel = opts.orgLevel;
    this.orgName = opts.orgName;
    this.orgSort = opts.orgSort;
    this.orgType = opts.orgType;
    this.orgTypeStr = Object.values(organTypes).find(
      i => i.code === opts.orgType
    ).name;
    this.superName = opts.superName;
    this.parentId = opts.parentId;
    this.hasChildren = this.orgType === organTypes.dw.code ? true : false;
    this.childs = [];
  }

  static instance(opts) {
    return new TreeNode(opts);
  }
}

//机构类型常量
const organTypes = {
  dw: { code: 0, name: "单位", icon: "" },
  bm: { code: 1, name: "部门", icon: "" }
};

export default {
  components: { AddOrUpdateOrgan },
  data() {
    return {
      isLoading:false,
      // collapse: false,
      tableHeight: 300,
      // 自定义查询
      customSearch: {},

      //分页
      currentPage: 1,
      total: 0,
      pageSize: 10,
      loading: false,

      tableData: null,

      //使用到的常量
      REQUEST_ERROR: "请求失败",
      organTypes: organTypes
    };
  },
  created() {
    window.onresize = null;
    this.caclTableHeight();
  },
  mounted() {
    this.isLoading = false
    this.findDefaultTableData({ parentId: 0 });
    window.onresize = () => {
      this.caclTableHeight();
    };
   
  },
  updated(){
    var _t = this
    let timer 
    setTimeout(function(){
      _t.isLoading = false
    },2000)
  },
  methods: {
     handleSizeChange(val) {
      this.pageSize = val;
      this.isLoading = true
      this.findDefaultTableData({ parentId: 0 });
      window.onresize = () => {
        this.caclTableHeight();
      };
    },
    caclTableHeight() {
      //  window.innerHeight - this.$refs.table.$el.offsetTop - 60 - 66;
      // 浏览器内部高度 - header高度-footer高度
      this.tableHeight = window.innerHeight - 126 -66;
    },
    //弹框方法 打开和关闭后回调
    openDialogVisible(type, row) {
      this.$refs.dialog.openDialogVisible(type, row);
    },
    dialogCallBack() {
      this.findDefaultTableData({ parentId: 0 });
    },

    // 搜索和重置
    search() {
      const search = this.customSearch.search;
      if (!search || search == "") {
        this.customSearch = { parentId: 0 };
      }
      this.findDefaultTableData(this.customSearch);
    },
    clearData() {
      this.customSearch = { parentId: 0 };
      this.findDefaultTableData(this.customSearch);
    },

    // 删除
    async deleteItem(row, ev) {
      try {
        //点解删除按钮隐藏tooltip提示 否则弹框取消后tooltip不消失
        ev.target.blur();

        await this.$confirm("此操作将永久删除该机构, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          cancelButtonClass: "el-button--primary",
          type: "warning"
        });

        const result = await deleteSysOrg({ ids: row.orgId });

        if (!result.success) {
          throw result;
        }

        this.findDefaultTableData({ parentId: 0 });
        this.$message.success("删除成功");
      } catch (error) {
        error !== "cancel" && this.$message.error(error.message);
      }
    },

    // 查询table 第一层数据并展开
    async findDefaultTableData(data) {
      this.loading = true;
      await this.findTableDataSync(data);
      this.loading = false;
      this.tableData && this.tableData.length > 0 && this.defaultExpand();
      
    },

    // 默认展开第一层
    defaultExpand() {
      const selector = ".orgTable .el-table__row--level-0 .el-icon";
      const iconList = document.querySelectorAll(selector);
      iconList.forEach(i => {
        i.click();
      });
    },

    // 根据机构分类获取icon
    findOrgIcon(type) {
      return Object.values(organTypes).find(i => i.code === type).icon;
    },

    pageChange(val) {
      this.currentPage = val;
      this.findDefaultTableData({ parentId: 0 });
    },

    // 查询机构分页数据
    async findTableDataSync(data) {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        ...data
      };

      try {
        const result = await findSysOrgPage(params);

        if (!result.success) {
          throw this.REQUEST_ERROR;
        }

        if (result.data.list.length == 0 && this.currentPage != 1) {
          --this.currentPage;
          this.findDefaultTableData({ parentId: 0 });
        } else {
          this.total = result.data.total;
          this.tableData = result.data.list.map(TreeNode.instance);          
        }
      } catch (error) {
        this.$message.error("数据获取失败");
      }
    },

    // 加载机构子节点数据
    async load(tree, treeNode, resolve) {
      let nodeData;
      try {
        const result = await getOrgTree({ parentId: tree.orgId });

        if (!result.success) {
          throw this.REQUEST_ERROR;
        }

        nodeData = result.data.map(i => {
          i.superName = tree.orgName;
          return new TreeNode(i);
        });
      } catch (error) {
        console.log(error);
        nodeData = [];
      } finally {
        resolve(nodeData);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
// table
/deep/ .el-table {
  .el-table__expand-icon {
    width: 20px;
    height: 20px;
    margin: 0;
    margin-left: -20px;
    & .el-icon-arrow-right:before {
      content: "\e7a0";
      color: #0090ff;
    }
    &.el-table__expand-icon--expanded .el-icon-arrow-right:before {
      content: "\e7a2";
      color: #0090ff;
    }
  }
  .el-icon-arrow-right {
    margin: 0;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 16px;
  }

  .el-table__expand-icon--expanded {
    -webkit-transform: none;
  }

  .enc-table-icon {
    vertical-align: middle;
    margin-right: 14px;
  }

  .el-table__row:hover {
    .unit {
      background: url("../../assets/images/unit-active.png") center -1px no-repeat;
    }
    .bumen {
      background-image: url("../../assets/images/section-active.png");
    }
  }
}

// icon

.unit {
  background: url("../../assets/images/unit.png") center center no-repeat;
  display: inline-block;
  width: 20px;
  height: 20px;
  vertical-align: middle;
}

.bumen {
  background: url("../../assets/images/section.png") center center no-repeat;
  display: inline-block;
  width: 20px;
  height: 20px;
  vertical-align: middle;
}

.plus-icon {
  padding: 4px;
  display: inline-block;
  color: #fff;
  background-color: #738291;
  border-radius: 4px;
  font-size: 14px;
  &:hover {
    background-color: #4b5fa1;
  }
  & .el-icon-plus:before {
    font-weight: bold;
  }
}
.Tableheight {
  height: 650px;
  overflow: auto;
}
.enc-pagination {
  float: right;
}
.mt-20{
  margin-top: 40px;
}

</style>
